<template>
  <div class="calendar-container">
    <div class="calendar-header">
      <el-button @click="previousMonth" :icon="ArrowLeft" />
      <h3>{{ currentYear }}年{{ currentMonth }}月</h3>
      <el-button @click="nextMonth" :icon="ArrowRight" />
    </div>

    <div class="calendar-grid">
      <!-- 星期标题 -->
      <div class="weekday-header">
        <div v-for="day in weekdays" :key="day" class="weekday">
          {{ day }}
        </div>
      </div>

      <!-- 日期格子 -->
      <div class="calendar-days">
        <div
          v-for="day in calendarDays"
          :key="day.date"
          class="calendar-day"
          :class="{
            'other-month': !day.isCurrentMonth,
            'today': day.isToday,
            'selected': isSelected(day.date),
            'has-homework': day.hasHomework
          }"
          @click="selectDate(day)"
        >
          <div class="day-number">{{ day.day }}</div>
          <!-- 作业状态指示器 -->
          <div v-if="day.hasHomework" class="status-indicator" :class="getStatusClass(day)">
            <div class="indicator-dot"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const props = defineProps({
  modelValue: {
    type: Date,
    default: () => new Date()
  },
  studentId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'date-select'])

const currentDate = ref(new Date())
const selectedDate = ref(props.modelValue)
const homeworkData = ref({}) // 存储有作业的日期
const homeworkStatusData = ref({}) // 存储作业状态数据

const weekdays = ['日', '一', '二', '三', '四', '五', '六']

const currentYear = computed(() => dayjs(currentDate.value).year())
const currentMonth = computed(() => dayjs(currentDate.value).month() + 1)

// 生成日历天数
const calendarDays = computed(() => {
  const startOfMonth = dayjs(currentDate.value).startOf('month')
  const endOfMonth = dayjs(currentDate.value).endOf('month')
  const startDate = startOfMonth.startOf('week')
  const endDate = endOfMonth.endOf('week')

  const days = []
  let current = startDate

  while (current.isBefore(endDate) || current.isSame(endDate)) {
    const dateStr = current.format('YYYY-MM-DD')
    const statusData = homeworkStatusData.value[dateStr]
    const dayData = {
      date: dateStr,
      day: current.date(),
      isCurrentMonth: current.month() === startOfMonth.month(),
      isToday: current.isSame(dayjs(), 'day'),
      hasHomework: homeworkData.value[dateStr] || false,
      status: statusData?.status || null, // 0: 未完成必须作业, 1: 已完成必须作业
      homeworkCount: statusData?.count || 0
    }

    // 特别记录16号和17号的渲染数据
    if (dateStr === '2025-10-16' || dateStr === '2025-10-17') {
      console.log(`📅 ${dateStr} 渲染数据:`, dayData)
    }

    days.push(dayData)
    current = current.add(1, 'day')
  }

  return days
})

const isSelected = (date) => {
  return dayjs(selectedDate.value).format('YYYY-MM-DD') === date
}

const getStatusClass = (day) => {
  if (day.status === null)  {
    if (day.homeworkCount !== null) {
      console.log('🔴 返回 incomplete class - 红色')
      return 'incomplete' // 红点 - 必须作业未完成
    }
    return 'no-status'
  }
  if (day.status === 0) {
    console.log('🔴 返回 incomplete class - 红色')
    return 'incomplete' // 红点 - 必须作业未完成
  }
  if (day.status === 1) {
    console.log('🟢 返回 completed class - 绿色')
    return 'completed' // 绿点 - 必须作业已完成
  }
  console.log('⚪ 返回 no-status class')
  return 'no-status'
}

const selectDate = (day) => {
  if (day.isCurrentMonth) {
    selectedDate.value = dayjs(day.date).toDate()
    emit('update:modelValue', selectedDate.value)
    emit('date-select', day.date)
  }
}

const previousMonth = () => {
  currentDate.value = dayjs(currentDate.value).subtract(1, 'month').toDate()
}

const nextMonth = () => {
  currentDate.value = dayjs(currentDate.value).add(1, 'month').toDate()
}

// 加载作业数据（从API获取）
const loadHomeworkData = async () => {
  if (!props.studentId) {
    console.log('📅 日历 - 学生ID不存在，跳过加载')
    homeworkData.value = {}
    homeworkStatusData.value = {}
    return
  }

  try {
    console.log('📅 日历 - 开始加载数据 - 学生ID:', props.studentId, '年:', currentYear.value, '月:', currentMonth.value)

    // 调用分析API获取日历数据
    const { analyticsApi } = await import('@/api/analytics')
    const response = await analyticsApi.getCalendarData(
      props.studentId,
      currentYear.value,
      currentMonth.value
    )

    console.log('📥 日历API响应:', response.data)

    // 处理返回的数据 - 根据后端AnalyticsService，实际数据在response.data.data中
    const monthData = {}
    const statusData = {}

    const actualData = response.data.data || []
    console.log('📊 日历数据记录数量:', actualData.length)

    if (actualData.length === 0) {
      console.log('❌ 日历 - 没有找到任何记录')
      homeworkData.value = {}
      homeworkStatusData.value = {}
      return
    }

    // 显示所有记录的关键信息
    console.log('📋 日历 - 所有记录详情:')
    actualData.forEach((item, index) => {
      console.log(`  ${index + 1}. ${item.title} - ${item.date}`)
      console.log(`     必须完成: ${item.total_required}, 已完成必须: ${item.required_completed}, 总数: ${item.total_items}`)
    })

    actualData.forEach(item => {
      const dateStr = dayjs(item.date).format('YYYY-MM-DD')
      monthData[dateStr] = true

      console.log(`🔍 处理日期 ${dateStr}:`, {
        title: item.title,
        total_required: item.total_required,
        required_completed: item.required_completed,
        total_items: item.total_items
      })

      // 根据作业完成状态设置状态指示
      if (item.total_required > 0) {
        // 有必须作业
        if (item.required_completed === item.total_required) {
          // 必须作业都完成 - 绿点
          statusData[dateStr] = {
            status: 1,
            count: item.total_items || 0
          }
          console.log(`🟢 ${dateStr} 设置为绿点 - 必须作业全部完成`)
        } else {
          // 必须作业未完成 - 红点
          statusData[dateStr] = {
            status: 0,
            count: item.total_items || 0
          }
          console.log(`🔴 ${dateStr} 设置为红点 - 必须作业未完成 (${item.required_completed}/${item.total_required})`)
        }
      } else {
        // 没有必须作业，但有作业 - 默认显示为完成（绿色）
        statusData[dateStr] = {
          status: 1,
          count: item.total_items || 0
        }
        console.log(`🟢 ${dateStr} 无必须作业但有作业 - 默认设置为绿点`)
      }
    })

    console.log('🎯 日历 - 最终状态数据:', statusData)

    // 特别检查16号和17号的数据
    console.log('🔍 特殊检查:')
    console.log('  16号数据:', {
      hasHomework: monthData['2025-10-16'],
      statusData: statusData['2025-10-16']
    })
    console.log('  17号数据:', {
      hasHomework: monthData['2025-10-17'],
      statusData: statusData['2025-10-17']
    })

    homeworkData.value = monthData
    homeworkStatusData.value = statusData
  } catch (error) {
    console.error('❌ 加载日历数据失败:', error)
    homeworkData.value = {}
    homeworkStatusData.value = {}
  }
}

// 监听月份变化
watch(currentDate, () => {
  loadHomeworkData()
})

// 监听学生ID变化
watch(() => props.studentId, () => {
  loadHomeworkData()
}, { immediate: true })

onMounted(() => {
  loadHomeworkData()
})
</script>

<style scoped>
.calendar-container {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 280px; /* 防止日历过度压缩 */
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.calendar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.calendar-grid {
  width: 100%;
}

.weekday-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
  margin-bottom: 6px;
}

.weekday {
  text-align: center;
  font-weight: bold;
  color: #666;
  font-size: 14px;
  padding: 6px 0;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
}

.calendar-day {
  /* 移除 aspect-ratio，改用更灵活的高度控制 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 4px;
  position: relative;
  transition: all 0.3s;
  min-height: 36px;
  height: clamp(32px, 4.5vw, 50px); /* 响应式高度，在32px-50px之间 */
  padding: 4px 2px;
}

.calendar-day:hover {
  background: #f0f9ff;
}

.calendar-day.other-month {
  color: #ccc;
  cursor: not-allowed;
}

.calendar-day.today {
  background: #3b82f6;
  color: white;
}

.calendar-day.selected {
  background: #1e40af;
  color: white;
}

.day-number {
  font-size: clamp(12px, 2.5vw, 16px); /* 响应式字体大小 */
  font-weight: 500;
  line-height: 1.2;
}

.status-indicator {
  position: absolute;
  bottom: 2px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1px;
}

.indicator-dot {
  width: clamp(4px, 1.2vw, 6px); /* 响应式指示器大小 */
  height: clamp(4px, 1.2vw, 6px);
  border-radius: 50%;
}

.status-indicator.incomplete .indicator-dot {
  background: #ef4444; /* 红色 - 必须作业未完成 */
}

.status-indicator.completed .indicator-dot {
  background: #10b981; /* 绿色 - 必须作业已完成 */
}

.homework-count {
  font-size: clamp(8px, 1.8vw, 10px); /* 响应式字体大小 */
  color: #666;
  font-weight: 500;
  line-height: 1;
}

/* 平板设备适配 */
@media (max-width: 1024px) {
  .calendar-container {
    padding: 12px;
    min-width: 260px;
  }

  .calendar-day {
    min-height: 32px;
    height: clamp(28px, 5vw, 40px);
  }

  .weekday {
    font-size: 13px;
    padding: 4px 0;
  }
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .calendar-container {
    padding: 8px;
    min-width: 240px;
  }

  .calendar-header h3 {
    font-size: 16px;
  }

  .weekday {
    font-size: 12px;
    padding: 3px 0;
  }

  .calendar-day {
    min-height: 28px;
    height: clamp(24px, 6vw, 32px);
    padding: 2px 1px;
  }

  .weekday-header,
  .calendar-days {
    gap: 1px;
  }
}

/* 小屏幕设备适配 */
@media (max-width: 480px) {
  .calendar-container {
    padding: 6px;
    min-width: 220px;
  }

  .calendar-day {
    min-height: 24px;
    height: clamp(20px, 7vw, 28px);
  }

  .day-number {
    font-size: clamp(10px, 3vw, 14px);
  }

  .indicator-dot {
    width: clamp(3px, 1.5vw, 4px);
    height: clamp(3px, 1.5vw, 4px);
  }
}
</style>